package com.cet6.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.cet6.dto.DailyWordDTO;
import com.cet6.dto.DailyStudyProgressDTO;
import com.cet6.entity.DailyTask;
import com.cet6.entity.StudyRecord;
import com.cet6.mapper.DailyTaskMapper;
import com.cet6.mapper.StudyRecordMapper;
import com.cet6.mapper.WordMapper;
import com.cet6.service.DailyStudyService;
import com.cet6.service.StudyRecordService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;

@Service
public class DailyStudyServiceImpl implements DailyStudyService {
    
    private static final int DAILY_WORD_COUNT = 15; // 每日推荐单词数量
    private static final int[] REVIEW_INTERVALS = {1, 3, 7, 15, 30}; // 复习间隔（天）
    
    @Autowired
    private WordMapper wordMapper;
    
    @Autowired
    private DailyTaskMapper dailyTaskMapper;
    
    @Autowired
    private StudyRecordMapper studyRecordMapper;
    
    @Autowired
    private StudyRecordService studyRecordService;
    
    @Override
    @Transactional
    public List<DailyWordDTO> getDailyWords(Long userId) {
        LocalDate today = LocalDate.now();
        
        // 1. 获取未学过的单词（优先）
        List<DailyWordDTO> unstudiedWords = wordMapper.selectUnstudiedWords(userId, DAILY_WORD_COUNT);
        
        List<DailyWordDTO> dailyWords = new ArrayList<>();
        dailyWords.addAll(unstudiedWords);
        
        // 2. 如果未学过的单词不足15个，用需要复习的单词补足
        int remainingCount = DAILY_WORD_COUNT - unstudiedWords.size();
        if (remainingCount > 0) {
            List<DailyWordDTO> reviewWords = wordMapper.selectReviewWords(userId, today, remainingCount);
            dailyWords.addAll(reviewWords);
        }
        
        // 3. 创建或更新每日任务
        createOrUpdateDailyTask(userId, today, dailyWords.size(), unstudiedWords.size(), 
                               dailyWords.size() - unstudiedWords.size());
        
        return dailyWords;
    }
    
    @Override
    @Transactional
    public boolean submitDailyProgress(DailyStudyProgressDTO progressDTO) {
        // 1. 更新学习记录
        boolean success = updateStudyRecord(progressDTO.getUserId(), progressDTO.getWordId(), 
                                          progressDTO.getResult(), progressDTO.getStudyType());
        
        if (success) {
            // 2. 更新每日任务完成数量
            updateDailyTaskProgress(progressDTO.getUserId(), LocalDate.now());
        }
        
        return success;
    }
    
    @Override
    public DailyTask getDailyTask(Long userId, LocalDate taskDate) {
        return dailyTaskMapper.selectByUserIdAndDate(userId, taskDate);
    }
    
    @Override
    @Transactional
    public DailyTask createOrUpdateDailyTask(Long userId, LocalDate taskDate, Integer totalWords, 
                                           Integer newWords, Integer reviewWords) {
        DailyTask existingTask = dailyTaskMapper.selectByUserIdAndDate(userId, taskDate);
        
        if (existingTask != null) {
            // 更新现有任务
            existingTask.setTotalWords(totalWords);
            existingTask.setNewWords(newWords);
            existingTask.setReviewWords(reviewWords);
            existingTask.setUpdateTime(LocalDateTime.now());
            dailyTaskMapper.updateById(existingTask);
            return existingTask;
        } else {
            // 创建新任务
            DailyTask newTask = new DailyTask();
            newTask.setUserId(userId);
            newTask.setTaskDate(taskDate);
            newTask.setTotalWords(totalWords);
            newTask.setCompletedWords(0);
            newTask.setNewWords(newWords);
            newTask.setReviewWords(reviewWords);
            newTask.setIsCompleted(0);
            newTask.setCreateTime(LocalDateTime.now());
            newTask.setUpdateTime(LocalDateTime.now());
            newTask.setDeleted(0);
            dailyTaskMapper.insert(newTask);
            return newTask;
        }
    }
    
    @Override
    @Transactional
    public boolean updateStudyRecord(Long userId, Long wordId, Integer result, Integer studyType) {
        try {
            // 获取或创建学习记录
            StudyRecord studyRecord = studyRecordMapper.selectByUserIdAndWordId(userId, wordId);
            
            if (studyRecord == null) {
                // 创建新记录
                studyRecord = new StudyRecord();
                studyRecord.setUserId(userId);
                studyRecord.setWordId(wordId);
                studyRecord.setStatus(1);
                studyRecord.setStudyCount(1);
                studyRecord.setLastStudyTime(LocalDateTime.now());
                studyRecord.setMasteryLevel(result == 1 ? 50 : 0);
                studyRecord.setReviewStage(0);
                studyRecord.setIsMastered(0);
                studyRecord.setCreateTime(LocalDateTime.now());
                studyRecord.setUpdateTime(LocalDateTime.now());
                studyRecord.setDeleted(0);
                
                // 计算下次复习日期
                studyRecord.setNextReviewDate(calculateNextReviewDate(studyRecord.getReviewStage(), result));
                
                studyRecordMapper.insert(studyRecord);
            } else {
                // 更新现有记录
                studyRecord.setStudyCount(studyRecord.getStudyCount() + 1);
                studyRecord.setLastStudyTime(LocalDateTime.now());
                
                // 应用复习调度算法
                int newReviewStage = calculateReviewStage(studyRecord.getReviewStage(), result);
                studyRecord.setReviewStage(newReviewStage);
                studyRecord.setNextReviewDate(calculateNextReviewDate(newReviewStage, result));
                
                // 更新掌握程度
                if (result == 1) {
                    studyRecord.setMasteryLevel(Math.min(100, studyRecord.getMasteryLevel() + 20));
                    if (studyRecord.getMasteryLevel() >= 100) {
                        studyRecord.setIsMastered(1);
                        studyRecord.setStatus(2);
                    }
                } else {
                    studyRecord.setMasteryLevel(Math.max(0, studyRecord.getMasteryLevel() - 10));
                }
                
                studyRecord.setUpdateTime(LocalDateTime.now());
                studyRecordMapper.updateById(studyRecord);
            }
            
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }
    
    /**
     * 计算复习阶段
     */
    private int calculateReviewStage(int currentStage, int result) {
        if (result == 1) {
            // 正确：进入下一阶段（最多到阶段5）
            return Math.min(5, currentStage + 1);
        } else {
            // 错误：退回前一阶段（最少为阶段0）
            return Math.max(0, currentStage - 1);
        }
    }
    
    /**
     * 计算下次复习日期
     */
    private LocalDate calculateNextReviewDate(int reviewStage, int result) {
        if (result == 1 && reviewStage > 0) {
            // 如果答对了且不是第一次学习，按复习间隔计算
            int days = REVIEW_INTERVALS[Math.min(reviewStage - 1, REVIEW_INTERVALS.length - 1)];
            return LocalDate.now().plusDays(days);
        } else {
            // 答错了或第一次学习，当天复习
            return LocalDate.now();
        }
    }
    
    /**
     * 更新每日任务进度
     */
    private void updateDailyTaskProgress(Long userId, LocalDate taskDate) {
        DailyTask task = dailyTaskMapper.selectByUserIdAndDate(userId, taskDate);
        if (task != null) {
            task.setCompletedWords(task.getCompletedWords() + 1);
            
            // 检查是否完成所有任务
            if (task.getCompletedWords() >= task.getTotalWords()) {
                task.setIsCompleted(1);
            }
            
            task.setUpdateTime(LocalDateTime.now());
            dailyTaskMapper.updateById(task);
        }
    }
}
